package com.edu.framework.websocket.service;

import cn.hutool.core.util.StrUtil;
import com.edu.common.core.cache.ICache;
import com.edu.framework.websocket.WebSocketHolder;
import com.edu.system.domain.TTerminal;
import com.edu.system.service.ITTerminalService;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

/**
 * @program: xxxx
 * @description:
 * @author: zlh
 * @create: 2024-01-06 18:20
 **/
@Slf4j
@Component
public class PingService {

  @Resource
  private ITTerminalService itTerminalService;
  @Resource
  private ICache iCache;

  private static String PING_KEY = "terminal_live_%s";
  // 0开机 1关机
  private static Integer TERMINAL_STATUS_ON = 0;
  private static Integer TERMINAL_STATUS_OFF = 1;

  public void handlePing(WebSocketSession session, Long ts){

    String code = WebSocketHolder.getCodeBySession(session);
    Integer timeout = 2;
    this.iCache.setCacheObject(this.getRedisKey(code), ts, timeout, TimeUnit.MINUTES);
  }

  /**
   * 更新开关机状态
   */
  public void changeStatus(){
    List<TTerminal> tList = itTerminalService.selectTTerminalList(new TTerminal());
    tList.forEach(a -> {
      Long c = this.iCache.getCacheObject(getRedisKey(a.getCode()));
      Integer status = TERMINAL_STATUS_OFF;
      Date date = new Date();
      if (Objects.nonNull(c) && (date.getTime() - c) < 12000){
        status = TERMINAL_STATUS_ON;
      }

      if (!a.getStatus().equals(status)){
        TTerminal entity = new TTerminal();
        entity.setId(a.getId());
        entity.setStatus(status);
        itTerminalService.updateTTerminal(entity);
      }

    });
  }

  private String getRedisKey(String code){
    return String.format(PING_KEY, code);
  }



}
